<template>
  <div class="task-schedule">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>策略配置</h3>

          <el-button type="primary" @click="handleSubmit">触发任务</el-button>
        </div>
        
          
      </template>

      <!-- 策略配置部分 -->
      <div class="strategy-config">
        <el-form :model="currentConfig" label-width="120px">
          <el-form-item label="设备型号">
            <el-select v-model="currentConfig.deviceId" placeholder="请选择设备型号" @change="handleDeviceChange">
              <el-option
                v-for="device in devices"
                :key="device.id"
                :label="device.name"
                :value="device.id"
              />
            </el-select>
            <el-button type="primary" @click="showAddDeviceDialog" style="margin-left: 10px">
              添加设备型号
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 策略列表配置 -->
        <div v-if="currentConfig.deviceId" class="strategies-list">
          <div v-for="(strategy, index) in currentConfig.strategies" :key="index" class="strategy-item">
            <el-divider>策略 {{ index + 1 }}</el-divider>
            <el-form :model="strategy" label-width="120px">
              <el-form-item label="策略描述">
                <el-input v-model="strategy.strategy_desc" placeholder="请输入策略描述"/>
              </el-form-item>
              
              <el-form-item label="执行时间">
                <el-checkbox-group v-model="strategy.weekdays">
                  <el-checkbox :value="'星期1'" label='星期1' border />
                  <el-checkbox :value="'星期2'" label='星期2' border />
                  <el-checkbox :value="'星期3'" label='星期3' border />
                  <el-checkbox :value="'星期4'" label='星期4' border />
                  <el-checkbox :value="'星期5'" label='星期5' border />
                  <el-checkbox :value="'星期6'" label='星期6' border />
                  <el-checkbox :value="'星期7'" label='星期7' border />

                </el-checkbox-group>
              </el-form-item>

              <el-form-item label="测试用例">
                <el-input v-model="strategy.test_case" placeholder="请输入测试用例名称"/>
              </el-form-item>

              <el-form-item>
                <el-button type="danger" @click="removeStrategy(index)" :disabled="index === 0">
                  删除策略
                </el-button>
              </el-form-item>
            </el-form>
          </div>

          <div class="strategy-actions">
            <el-button 
              type="primary" 
              @click="addStrategy" 
              :disabled="currentConfig.strategies.length >= 5"
            >
              添加策略
            </el-button>
            <el-button type="success" @click="saveStrategies">保存配置</el-button>
          </div>
        </div>
      </div>

      <!-- 策略展示列表 -->
      <el-divider>当前策略列表</el-divider>
      <el-table :data="groupedStrategies" style="width: 100%">
        <el-table-column type="expand">
          <template #default="props">
            <el-table :data="props.row.strategies" border>
              <el-table-column prop="strategy_desc" label="策略描述" />
              <el-table-column prop="weekdays" label="执行时间" />
              <el-table-column prop="test_case" label="测试用例" />
            </el-table>
          </template>
        </el-table-column>
        <el-table-column prop="device_name" label="设备型号" />
        <el-table-column prop="strategy_count" label="策略数量" />
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <el-button 
              type="primary" 
              @click="triggerJob(scope.row.device_id)"
              size="small"
            >
              执行
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加设备型号对话框 -->
    <el-dialog v-model="addDeviceDialogVisible" title="添加设备型号" width="30%">
      <el-form :model="newDevice" label-width="120px">
        <el-form-item label="设备型号名称">
          <el-input v-model="newDevice.name" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDeviceDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addDevice">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import request from '@/utils/request.js'  // 修改为你的实际路径

const devices = ref([])
const addDeviceDialogVisible = ref(false)
const newDevice = ref({ name: '' })
const strategies = ref([])

const currentConfig = ref({
  deviceId: '',
  strategies: [{
    strategy_desc: '',
    weekdays: [],
    test_case: '',
    run_times: 5
  }]
})


const handleSubmit = async () => {
  try {
    const response = await request.post('/schedule_job', {})  // 不需要 /api 前缀
    if (response.data.status === 'success') {
      ElMessage.success('任务触发成功')
    } else {
      ElMessage.error(response.data.message || '任务触发失败')
    }
  } catch (error) {
    ElMessage.error('请求失败：' + error.message)
  }
}

const fetchDevices = async () => {
  try {
    const response = await request.get('/devices')  // 不需要 /api 前缀
    if (response.data.status === 'success') {
      devices.value = response.data.data
    }
  } catch (error) {
    ElMessage.error('获取设备列表失败')
  }
}

const fetchStrategies = async () => {
  try {
    const response = await request.get('/strategies')  // 不需要 /api 前缀
    if (response.data.status === 'success') {
      strategies.value = response.data.data
    }
  } catch (error) {
    ElMessage.error('获取策略列表失败')
  }
}

const addDevice = async () => {
  try {
    const response = await request.post('/devices', newDevice.value)  // 不需要 /api 前缀
    if (response.data.status === 'success') {
      ElMessage.success('添加成功')
      addDeviceDialogVisible.value = false
      newDevice.value.name = ''
      await fetchDevices()
    }
  } catch (error) {
    ElMessage.error('添加设备失败')
  }
}

const saveStrategies = async () => {
  try {
    const response = await request.post('/strategies', {  // 不需要 /api 前缀
      device_id: currentConfig.value.deviceId,
      strategies: currentConfig.value.strategies
    })
    if (response.data.status === 'success') {
      ElMessage.success('保存成功')
      await fetchStrategies()
    }
  } catch (error) {
    ElMessage.error('保存失败')
  }
}

const triggerJob = async (deviceId) => {
  try {
    const response = await request.post('/schedule_job', { device_id: deviceId })  // 不需要 /api 前缀
    if (response.data.status === 'success') {
      ElMessage.success('任务触发成功')
    }
  } catch (error) {
    ElMessage.error('任务触发失败')
  }
}

// 显示添加设备对话框
const showAddDeviceDialog = () => {
  addDeviceDialogVisible.value = true
}

onMounted(async () => {
  await fetchDevices()
  await fetchStrategies()
})
</script>

<style scoped>
.task-schedule {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.strategy-config {
  margin-top: 20px;
}

.strategy-item {
  margin-bottom: 20px;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.strategy-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.el-checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
</style>